/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.spring.bean;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.pajamas.protocol.Builder;
import org.pajamas.starter.core.util.ClasspathUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author william
 * @since 2024/1/16
 */
public final class CandidateBeanDefSetBuilder implements Builder<Set<BeanDefinition>> {
    private final Environment environment;
    private final ResourceLoader resourceLoader;

    private final Set<String> basePackages;

    private final List<TypeFilter> includeFilters;

    private final List<TypeFilter> excludeFilters;

    private CandidateBeanDefSetBuilder(Environment environment, ResourceLoader resourceLoader) {
        this.environment = environment;
        this.resourceLoader = resourceLoader;
        this.basePackages = Sets.newHashSet();
        this.includeFilters = Lists.newArrayList();
        this.excludeFilters = Lists.newArrayList();
    }

    public static CandidateBeanDefSetBuilder newBuilder(Environment environment, ResourceLoader resourceLoader) {
        return new CandidateBeanDefSetBuilder(environment, resourceLoader);
    }

    public CandidateBeanDefSetBuilder basePackage(String basePackage) {
        this.basePackages.add(basePackage);
        return this;
    }

    public CandidateBeanDefSetBuilder currentBasePackage() {
        String currentBasePackage = ClasspathUtils.getCurrentBasePackage();
        return this.basePackage(currentBasePackage);
    }

    public CandidateBeanDefSetBuilder starterBasePackage() {
        return this.basePackage("org.pajamas.starter");
    }

    public CandidateBeanDefSetBuilder insteadOf(Class<?> superClass) {
        AssignableTypeFilter filter = new AssignableTypeFilter(superClass);
        this.includeFilters.add(filter);
        return this;
    }

    public CandidateBeanDefSetBuilder annotated(Class<? extends Annotation> annotationClass) {
        AnnotationTypeFilter filter = new AnnotationTypeFilter(annotationClass);
        this.includeFilters.add(filter);
        return this;
    }

    public CandidateBeanDefSetBuilder notInsteadOf(Class<?> superClass) {
        AssignableTypeFilter filter = new AssignableTypeFilter(superClass);
        this.excludeFilters.add(filter);
        return this;
    }

    public CandidateBeanDefSetBuilder notAnnotated(Class<? extends Annotation> annotationClass) {
        AnnotationTypeFilter filter = new AnnotationTypeFilter(annotationClass);
        this.excludeFilters.add(filter);
        return this;
    }

    @Override
    public Set<BeanDefinition> build() {
        if (ObjectUtils.anyNull(this.environment, this.resourceLoader)) {
            throw new RuntimeException();
        }

        List<String> handledBasePackages =
                this.basePackages.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(handledBasePackages)) {
            throw new RuntimeException();
        }

        ClassPathScanningCandidateComponentProvider beanDefScanner =
                new ClassPathScanningCandidateComponentProvider(false);
        beanDefScanner.setEnvironment(this.environment);
        beanDefScanner.setResourceLoader(this.resourceLoader);
        if (CollectionUtils.isNotEmpty(this.includeFilters)) {
            this.includeFilters.forEach(beanDefScanner::addIncludeFilter);
        }
        if (CollectionUtils.isNotEmpty(this.excludeFilters)) {
            this.excludeFilters.forEach(beanDefScanner::addExcludeFilter);
        }

        return handledBasePackages
                .stream()
                .map(beanDefScanner::findCandidateComponents)
                .filter(CollectionUtils::isNotEmpty)
                .flatMap(Set::stream)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }
}
